import { ratedApi, moviesApi, getMoreApi } from "@/api/home.js";

const hotModule = {
  namespaced: true,
  state() {
    return {
      // 最受欢迎数据
      ratedList: [],
      // 电影列表
      moviesList: [],
      ids: [],
      count: 0,
    };
  },

  mutations: {
    getRated(state, payload) {
      state.ratedList = payload.result;
    },
    getMovies(state, payload) {
      state.moviesList = payload.result;
      state.count = payload.count;
      state.ids = payload.ids;
    },
    getMore(state, payload) {
      state.moviesList = [...state.moviesList, ...payload.result];
    },
  },

  actions: {
    // 最受欢迎的列表请求
    asyncGetRated({ commit }) {
      // return promise的目的是为了在组件里面去使用.then
      return new Promise((resolve, reject) => {
        ratedApi().then((res) => {
          commit("getRated", res);
          resolve();
        });
      });
    },
    // 电影列表的请求
    asyncGetMovies({ commit }) {
      return new Promise((resolve) => {
        moviesApi().then((res) => {
          // console.log(res);
          commit("getMovies", res);
          resolve();
        });
      });
    },
    // 上拉加载
    asyncGetMore({ commit, state }) {
      return new Promise((resolve) => {
        // console.log(context);
        const arr = state.ids.slice(
          state.moviesList.length,
          state.moviesList.length + 6
        );
        getMoreApi({ ids: arr.join(",") }).then((res) => {
          // console.log(res);
          commit("getMore", res);
          resolve(state.moviesList.length === state.count);
        });
      });
    },
  },
};

export default hotModule;
